<?php

namespace app\admin\controller\scanwork;

use app\common\controller\Backend;
use app\admin\model\scanwork\QualityInventory as QualityInventoryModel;
use app\admin\model\scanwork\QualityInventoryDetail;
use app\admin\model\scanwork\QualityRecord;
use think\Db;
use think\exception\DbException;
use think\exception\ValidateException;

/**
 * 质检入库管理
 */
class QualityInventory extends Backend
{
    /**
     * QualityInventory模型对象
     * @var \app\admin\model\scanwork\QualityInventory
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new QualityInventoryModel;
    }

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            
            // 手动处理参数
            $sort = $this->request->get('sort', 'id');
            $order = $this->request->get('order', 'desc');
            $offset = $this->request->get('offset', 0);
            $limit = $this->request->get('limit', 10);
            
            // 构建查询条件
            $where = [];
            
            // 处理搜索条件
            $filter = $this->request->get('filter', '{}');
            $filter = json_decode($filter, true);
            if (is_array($filter)) {
                foreach ($filter as $key => $value) {
                    if ($value !== '' && $value !== null) {
                        $where[$key] = ['like', '%' . $value . '%'];
                    }
                }
            }
            
            $list = $this->model
                ->with([
                    'report', 
                    'allocation', 
                    'allocation.plan',
                    'allocation.order',
                    'order',
                    'productModel', 
                    'process',
                    'user',
                    'qualityUser',
                    'inventoryUser'
                ])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id', 'report_id', 'quantity', 'qualified_quantity', 'unqualified_quantity', 
                    'quality_result', 'quality_result_text', 'inventory_status', 'inventory_status_text',
                    'handle_method', 'handle_method_text', 'check_time', 'inventory_time', 'createtime']);
                    
                if ($row->allocation) {
                    $row->visible(['allocation']);
                    if ($row->allocation->plan) {
                        $row->allocation->visible(['plan']);
                    }
                    if ($row->allocation->order) {
                        $row->allocation->visible(['order']);
                    }
                }
                if ($row->order) {
                    $row->visible(['order']);
                }
                if ($row->productModel) {
                    $row->visible(['productModel']);
                    $row->getRelation('productModel')->visible(['name']);
                }
                if ($row->process) {
                    $row->visible(['process']);
                    $row->getRelation('process')->visible(['name']);
                }
                if ($row->user) {
                    $row->visible(['user']);
                    $row->getRelation('user')->visible(['nickname', 'username']);
                }
                if ($row->qualityUser) {
                    $row->visible(['qualityUser']);
                    $row->getRelation('qualityUser')->visible(['nickname', 'username']);
                }
                if ($row->inventoryUser) {
                    $row->visible(['inventoryUser']);
                    $row->getRelation('inventoryUser')->visible(['nickname', 'username']);
                }
            }
            
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    
    /**
     * 待入库列表
     */
    public function pending()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            // 手动处理参数
            $sort = $this->request->get('sort', 'id');
            $order = $this->request->get('order', 'desc');
            $offset = $this->request->get('offset', 0);
            $limit = $this->request->get('limit', 10);
            
            // 构建查询条件 - 只显示待入库的记录
            $where = ['inventory_status' => 0];
            
            // 处理搜索条件
            $filter = $this->request->get('filter', '{}');
            $filter = json_decode($filter, true);
            if (is_array($filter)) {
                foreach ($filter as $key => $value) {
                    if ($value !== '' && $value !== null) {
                        $where[$key] = ['like', '%' . $value . '%'];
                    }
                }
            }
            
            $list = $this->model
                ->with([
                    'report', 
                    'allocation', 
                    'allocation.plan',
                    'allocation.order',
                    'order',
                    'productModel', 
                    'process',
                    'user',
                    'qualityUser'
                ])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id', 'report_id', 'quantity', 'qualified_quantity', 'unqualified_quantity', 
                    'quality_result', 'quality_result_text', 'inventory_status', 'inventory_status_text',
                    'handle_method', 'handle_method_text', 'check_time', 'createtime']);
                    
                if ($row->allocation) {
                    $row->visible(['allocation']);
                    if ($row->allocation->plan) {
                        $row->allocation->visible(['plan']);
                    }
                    if ($row->allocation->order) {
                        $row->allocation->visible(['order']);
                    }
                }
                if ($row->order) {
                    $row->visible(['order']);
                }
                if ($row->productModel) {
                    $row->visible(['productModel']);
                    $row->getRelation('productModel')->visible(['name']);
                }
                if ($row->process) {
                    $row->visible(['process']);
                    $row->getRelation('process')->visible(['name']);
                }
                if ($row->user) {
                    $row->visible(['user']);
                    $row->getRelation('user')->visible(['nickname', 'username']);
                }
                if ($row->qualityUser) {
                    $row->visible(['qualityUser']);
                    $row->getRelation('qualityUser')->visible(['nickname', 'username']);
                }
            }
            
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    
    /**
     * 执行入库
     */
    public function execute($ids = null)
    {
        $ids = $ids ?: $this->request->get('id');
        if (!$ids) {
            // 返回标准JSON格式，包含状态码、错误消息
            return json(['code' => 0, 'msg' => '参数错误', 'data' => []]);
        }
        
        $inventory = QualityInventoryModel::with([
            'report', 
            'allocation', 
            'allocation.plan',
            'allocation.order',
            'order',
            'productModel', 
            'process',
            'user',
            'qualityUser'
        ])->find($ids);
        
        if (!$inventory) {
            // 返回标准JSON格式，包含状态码、错误消息
            return json(['code' => 0, 'msg' => '质检入库记录不存在', 'data' => []]);
        }
        
        if ($inventory->inventory_status == 1) {
            // 返回标准JSON格式，包含状态码、错误消息
            return json(['code' => 0, 'msg' => '该记录已入库，无需重复操作', 'data' => []]);
        }
        
        if ($this->request->isPost()) {
            // 获取带row前缀的参数
            $params = $this->request->post('row/a');
            
            // 执行入库操作
            Db::startTrans();
            try {
                // 更新入库状态
                $inventory->inventory_status = 1;
                $inventory->inventory_time = time();
                $inventory->inventory_user_id = $this->auth->id;
                
                // 如果有提交的参数，更新相应字段
                if (!empty($params)) {
                    if (isset($params['inventory_quantity'])) {
                        $inventory->inventory_quantity = $params['inventory_quantity'];
                    }
                    if (isset($params['storage_id'])) {
                        $inventory->storage_id = $params['storage_id'];
                    }
                    if (isset($params['remark'])) {
                        $inventory->remark = $params['remark'];
                    }
                }
                
                $inventory->save();
                
                // 更新质检记录的入库状态
                QualityRecord::where('report_id', $inventory->report_id)
                    ->update(['inventory_status' => 1]);
                
                Db::commit();
                // 返回标准JSON格式，包含状态码、消息和数据
                return json([
                    'code' => 1, 
                    'msg' => '入库成功', 
                    'data' => []
                ]);
            } catch (\Exception $e) {
                Db::rollback();
                // 返回标准JSON格式，包含状态码、错误消息
                return json(['code' => 0, 'msg' => $e->getMessage(), 'data' => []]);
            }
        }
        
        // 解析检查结果
        $checkResults = $this->parseCheckResults($inventory->check_results);
        
        $this->view->assign("inventory", $inventory);
        $this->view->assign("checkResults", $checkResults);
        return $this->view->fetch();
    }
    
    /**
     * 查看详情
     */
    public function detail($ids = null)
    {
        $ids = $ids ?: $this->request->get('id');
        if (!$ids) {
            $this->error('参数错误');
        }
        
        $inventory = QualityInventoryModel::with([
            'report', 
            'allocation', 
            'allocation.plan',
            'allocation.order',
            'order',
            'productModel', 
            'process',
            'user',
            'qualityUser',
            'inventoryUser',
            'details',
            'images'
        ])->find($ids);
        
        if (!$inventory) {
            $this->error('质检入库记录不存在');
        }
        
        // 解析检查结果
        $checkResults = $this->parseCheckResults($inventory->check_results);
        
        $this->view->assign("inventory", $inventory);
        $this->view->assign("checkResults", $checkResults);
        return $this->view->fetch();
    }
    
    /**
     * 解析检查结果JSON
     */
    private function parseCheckResults($jsonStr)
    {
        if (empty($jsonStr)) {
            return [];
        }
        
        // 先尝试直接解码
        $results = json_decode($jsonStr, true);
        
        // 如果解码失败，尝试处理转义
        if (!$results || !is_array($results)) {
            // 将 \\u 替换为 \u
            $jsonStr = str_replace('\\\\u', '\u', $jsonStr);
            $results = json_decode($jsonStr, true);
        }
        
        if (!$results || !is_array($results)) {
            return [];
        }
        
        return $results;
    }
}
